package com.price.common.util

import java.util.Locale

//十六进制转十进制
fun String.hexToDec(): Int {
    var result = 0
    for (element in this) {
        val digit = element.digitToIntOrNull(16) ?: -1
        result = result * 16 + digit
    }
    return result
}
fun String.hexStringToBytes(): ByteArray? {
    var hexString = this
    if (hexString.isEmpty()) {
        return null
    }
    hexString = hexString.uppercase(Locale.getDefault())
    val length = hexString.length / 2
    val hexChars = hexString.toCharArray()
    val d = ByteArray(length)
    for (i in 0 until length) {
        val pos = i * 2
        d[i] =
            (charToByte(hexChars[pos]).toInt() shl 4 or charToByte(hexChars[pos + 1]).toInt()).toByte()
    }
    return d
}

private fun charToByte(c: Char): Byte {
    return "0123456789ABCDEF".indexOf(c).toByte()
}

fun ByteArray.bytesToHex(): String? {
    if (this.isEmpty()) {
        return null
    }
    val sb = StringBuilder("")
    for (i in this.indices) {
        val value = this[i].toInt() and 0xFF
        val hv = Integer.toHexString(value)
        if (hv.length < 2) {
            sb.append(0)
        }
        sb.append("0x").append(hv).append(" ")
    }
    return sb.toString()
}

fun Byte.toByteString(): String {
    var hex = Integer.toHexString(this.toInt() and 0xFF)
    if (hex.length == 1) {
        hex = "0$hex"
    }
    return hex.uppercase(Locale.getDefault())
}
